package com.example.thread;

import javax.annotation.security.RunAs;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: ThreadFactory
 * @Description: 相当于重写Thread的工具类
 * @Author:
 * @Date
 */
public class SimpleThreadFactory  implements ThreadFactory {
    
      private final int maxThread;
      private final String threadGroupName;
      private final String threadNamePrefix;
      private final AtomicInteger count = new AtomicInteger(0);
      private final AtomicInteger threadSeq = new AtomicInteger(0);
      private final ThreadGroup threadGroup;


    public SimpleThreadFactory(int maxThread, String threadGroupName, String threadNamePrefix) {
        this.maxThread = maxThread;
        this.threadGroupName = threadGroupName;
        this.threadNamePrefix = threadNamePrefix;
        this.threadGroup =  new ThreadGroup(threadGroupName);;
    }

    @Override
    public Thread newThread(Runnable r) {
        int c = count.incrementAndGet();
        if (c > maxThread) {
            return null;
        }
        Thread thread = new Thread(threadGroup, r, threadNamePrefix + threadSeq.getAndIncrement());
        // 是否开启守护线程??
        thread.setDaemon(false);
        // 设置优先级
        thread.setPriority(Thread.NORM_PRIORITY);
        return thread;
    }


    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ThreadFactory factory = new SimpleThreadFactory(10, "thread-group-name-1", "thread");
         Thread t = factory.newThread(new Runnable() {
             @Override
             public void run() {
                 System.out.println("this is task");

                 countDownLatch.countDown();
             }
         });
         t.start();
         countDownLatch.await();
    }
}
